<template>
  <div>
    <el-row class="customRow">
      <el-col :span="1" style="height: 100px; line-height: 100px; "><span>类别</span></el-col>
      <el-col :span="2" style="height: 100px; line-height: 100px; ">
        <el-select v-model="toolOrder.orderType" size="mini" placeholder="请选择">
          <el-option
              v-for="item in optionsOrder"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="18">
        <el-row v-if="toolOrder.orderType == '外部订单'">
          <el-col :span="8">
            <span>客户名称</span>
            <el-autocomplete style="width: 100%" size="mini"
                             class="inline-input"
                             v-model="toolOrder.companyName"
                             :fetch-suggestions="querySearchCompany"
                             placeholder="请选择"
                             @select="handleSelect"
            ></el-autocomplete>
          </el-col>
          <el-col :span="16" style="display: flex; flex-wrap: wrap">
            <el-row>
              <el-col :span="6">
                <span>订货人</span>
                <el-autocomplete style="width: 100%" size="mini"
                                 class="inline-input"
                                 v-model="toolOrder.contactsName"
                                 :fetch-suggestions="querySearchContact"
                                 placeholder="请选择"
                                 @select="handleSelectContact"
                ></el-autocomplete>
              </el-col>
              <el-col :span="6"><span>电话</span>
                <el-input style="width: 100%" size="mini" disabled="true"
                          class="inline-input"
                          v-model="toolOrder.contactsMobile"
                ></el-input>
              </el-col>
              <el-col :span="6"><span>职务</span>
                <el-input style="width: 100%" size="mini" disabled="true"
                          class="inline-input"
                          v-model="toolOrder.contactsDuties"
                ></el-input>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6"><span>收货人</span>
                <el-autocomplete style="width: 100%" size="mini"
                                 class="inline-input"
                                 v-model="toolOrder.cargoReceiver"
                                 :fetch-suggestions="querySearchAddress"
                                 placeholder="请选择"
                                 @select="handleSelectAddress"
                ></el-autocomplete>
              </el-col>
              <el-col :span="6"><span>电话</span>
                <el-input style="width: 100%" size="mini" disabled="true"
                          class="inline-input"
                          v-model="toolOrder.cargoReceiverMobile"
                ></el-input>
              </el-col>
              <el-col :span="12"><span>地址</span>
                <el-input style="width: 100%" size="mini" disabled="true"
                          class="inline-input"
                          v-model="toolOrder.address"
                ></el-input>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row v-if="toolOrder.orderType == '内部订单'">
          <el-col :span="5"><span>分类</span>
            <el-select v-model="value" placeholder="请选择" size="mini">
              <el-option
                  v-for="item in optionsInternalOrders"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="7" v-if="toolOrder.orderType == '内部订单' && value == 'option1'"><span>设备编号</span>
            <el-input size="mini"></el-input>
          </el-col>
          <el-col :span="12" v-if="toolOrder.orderType == '内部订单' && value == 'option1'"><span>客户名称</span>
            <el-input size="mini"></el-input>
          </el-col>
          <el-col :span="7" v-if="toolOrder.orderType == '内部订单' && value == 'option2'"><span>项目编号</span>
            <el-input size="mini"></el-input>
          </el-col>
          <el-col :span="12" v-if="toolOrder.orderType == '内部订单' && value == 'option2'"><span>产品名称</span>
            <el-input size="mini"></el-input>
          </el-col>
          <el-col :span="7" v-if="toolOrder.orderType == '内部订单' && value == 'option3'"><span>客户名称</span>
            <el-input size="mini"></el-input>
          </el-col>
          <el-col :span="12" v-if="toolOrder.orderType == '内部订单' && value == 'option3'" style="min-width: 600px"><span>简要说明</span>
            <el-input size="mini" type="textarea" rows="2"></el-input>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="3" style="line-height: 20px; display: inline; text-align: left; padding-top: 5px">
        <el-upload class="upload-demo"
                   :action="uploadAction"
                   :file-list="fileListOrder" :multiple="false"
                   :on-success="(response, file, fileList) => handleUploadOrderAttachment(response, file, fileList)">
          <i class="el-icon-upload" style="color: #8CC5FF"></i>
          <el-button size="medium" type="text">合同/订单上传</el-button>
        </el-upload>

      </el-col>
    </el-row>

    <el-table
        :data="toolOrder.toolOrderItemDTOS"
        style="width: 100%" size="mini" border>
      <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
      <el-table-column label="产品名称" width="300" align="center">
        <template slot-scope="scope">
          <el-select v-model="scope.row.name" placeholder="请选择" style="width: 100%;">
            <el-option
                v-for="item in  optionsOrderItem"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="100" label="图纸" align="center">
        <template slot-scope="scope">
          <el-upload class="upload-demo"
                     :action="uploadAction"
                     :file-list="fileListDrawing" :multiple="false" :show-file-list="false"
                     :on-success="(response, file, fileList) => handleUploadItemAttachment(response, file, fileList, scope.$index)">
            <el-button size="small" type="text">选择</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column label="图号" width="300" align="center">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.drawingNumber" :disabled="true"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="150" align="center">
        <template slot-scope="scope">
          <el-input size="mini" v-model.number="scope.row.number"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="150" align="center">
        <template slot-scope="scope">
          <el-input size="mini" v-model.number="scope.row.unitPrice"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="总价" width="150" align="center">
        <template slot-scope="scope">
          <el-input size="mini" :value="(scope.row.number * scope.row.unitPrice).toFixed(2)"
                    :disabled="true"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="交货时间" width="250" align="center">
        <template slot-scope="scope">
          <el-date-picker
              v-model="scope.row.requestDeliveryTime"
              type="date"
              size="mini" style="width: 100%">
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column
          width="100" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-plus" @click="addRow"></el-button>
          <el-button type="text" size="mini" icon="el-icon-minus" v-if="toolOrder.toolOrderItemDTOS.length > 1"
                     @click="deleteRow(scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="onSubmit" size="mini">提 交</el-button>
        <el-button type="warning" @click="cancle" size="mini">取 消</el-button>
      </el-col>
    </el-row>
  </div>

</template>

<script>
export default {
  name: "CreateToolOrder",
  data() {
    return {
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      toolOrder: {
        orderType: '外部订单',
        companyName: '',
        contactsName: '',
        contactsDuties: '',
        contactsMobile: '',
        cargoReceiver: '',
        cargoReceiverMobile: '',
        address: '',
        contract: '',
        toolOrderItemDTOS: [{
          name: '',
          toolAttachments: [],
          number: '',
          unitPrice: '',
          amountMoney: '',
          drawingNumber: '',
          requestDeliveryTime: ''
        }]
      },
      fileListDrawing: [],
      fileListOrder: [],
      optionsOrder: [
        {
          value: '外部订单',
          label: '外部订单'
        },
        {
          value: '内部订单',
          label: '内部订单'
        },
      ],
      optionsOrderItem: [
        {
          value: '搅拌头',
          label: '搅拌头'
        }, {
          value: '刀柄',
          label: '刀柄'
        }, {
          value: '静轴肩搅拌针',
          label: '静轴肩搅拌针'
        }, {
          value: '静轴肩端盖',
          label: '静轴肩端盖'
        }, {
          value: '回抽搅拌针',
          label: '回抽搅拌针'
        }],
      optionsInternalOrders: [
        {
          value: 'option1',
          label: '设备配套'
        },
        {
          value: 'option2',
          label: '产品加工'
        },
        {
          value: 'option3',
          label: '客户试用'
        },
      ],
      value: 'option1',
    }
  },
  methods: {
    querySearchCompany(queryString, cb) {
      this.$http.get("custom/company_name").then(response => {
        const suggestions = response.data.data.map(companyName => {
          return {value: companyName};
        });
        cb(suggestions);
      })
    },
    querySearchContact(queryString, cb) {
      const companyName = this.toolOrder.companyName;
      if (!companyName) {
        // 可以选择返回空数组或者显示提示信息
        this.$message({
          message: '请先选择客户',
          type: 'warning'
        });
        cb([]);
        return;
      }
      this.$http.get(`custom/${companyName}/contacts`).then(response => {
        console.log(response.data)
        const suggestions = response.data.data.map(contact => {
          return {
            value: contact.contactsName,
            name: contact.contactsName,
            duty: contact.contactsDuties,
            phone: contact.contactsMobile
          };
        });
        cb(suggestions);
      });
    },
    querySearchAddress(queryString, cb) {
      const companyName = this.toolOrder.companyName
      if (!companyName) {
        // 可以选择返回空数组或者显示提示信息
        this.$message({
          message: '请先选择客户',
          type: 'warning'
        });
        cb([]);
        return;
      }
      this.$http.get(`custom/${companyName}/address`).then(response => {
        const suggestions = response.data.data.map(receivingAddress => {
          return {
            value: receivingAddress.cargoReceiver,
            name: receivingAddress.cargoReceiver,
            phone: receivingAddress.cargoReceiverMobile,
            address: receivingAddress.address
          };
        });
        cb(suggestions);
      })
    },
    handleSelect(item) {

    },
    handleSelectAddress(item) {
      this.toolOrder.cargoReceiver = item.name;
      this.toolOrder.cargoReceiverMobile = item.phone;
      this.toolOrder.address = item.address;
    },
    handleSelectContact(item) {
      this.toolOrder.contactsName = item.name;
      this.toolOrder.contactsMobile = item.phone;
      this.toolOrder.contactsDuties = item.duty;// 自动填充电话号码
    },
    addRow() {
      this.toolOrder.toolOrderItemDTOS.push({
        name: '',
        toolAttachments: [],
        number: '',
        unitPrice: '',
        amountMoney: '',
        drawingNumber: '',
        requestDeliveryTime: ''
      })
    },
    deleteRow(index) {
      if (this.toolOrder.toolOrderItemDTOS.length > 1) {
        this.toolOrder.toolOrderItemDTOS.splice(index, 1)
      }
    },
    handleUploadOrderAttachment(response, file, fileList) {
      const filePath = response.data
      this.toolOrder.contract = {
        filePath: filePath
      }
    },
    handleUploadItemAttachment(response, file, fileList, rowIndex) {
      console.log(response)
      const filePath = response.data
      this.toolOrder.toolOrderItemDTOS[rowIndex].toolAttachments.push(
          {
            filePath: filePath
          }
      )
      let fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
      fileName = fileName.substring(0, fileName.lastIndexOf('.'))
      this.toolOrder.toolOrderItemDTOS[rowIndex].drawingNumber = fileName;
    },
    updateAmounts() {
      this.toolOrder.toolOrderItemDTOS.forEach(item => {
        item.amountMoney = (parseFloat(item.number) * parseFloat(item.unitPrice)).toFixed(2);
        const date = new Date(item.requestDeliveryTime);
        item.requestDeliveryTime = `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
      });
    },
    onSubmit() {
      this.updateAmounts()
      console.log(JSON.stringify(this.toolOrder, null, 2))
      this.$http.post("/tool/addOrder", this.toolOrder).then(response => {
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "订单已提交"})
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
      })
    },
    cancle() {
    }
  }
}
</script>

<style scoped>

::v-deep .upload-demo .el-upload__list {
  flex-grow: 1;
  margin-left: 10px; /* 与按钮保持一定距离 */
  font-size: 10px; /* 调整文件列表的字体大小 */
}

::v-deep .upload-demo .el-upload__list__item {
  line-height: normal; /* 调整行高，如果需要 */
}

::v-deep .el-row.customRow {
  display: flex;
  justify-content: space-between !important;
  font-size: 12px;
  text-align: center;
  height: 100px;
  border: 1px solid #ccc;
  margin: 0;
  padding: 0;
}

::v-deep .el-row.customRow > .el-col {
  border-right: 1px solid #ccc;
  padding: 0 5px;
  display: flex;
  align-items: center;
  justify-content: left;
}

::v-deep .el-row.customRow .el-col .el-row {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: left !important;
  align-items: center;
  height: 50px;
}

::v-deep .el-row.customRow .el-col .el-row .el-col {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .customRow .el-col .el-row .el-col > span {
  width: 80px;
}

</style>